﻿<%@ WebHandler Language="C#" Class="WorkreportAndPlanRateReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 各工区报工及排产率查询报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.4.15
 **/

public class WorkreportAndPlanRateReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        DataTable dtResult = getData(jObject);
                        r.data = dtResult;
                        r.total = Convert.ToInt32(dtResult.Rows.Count);
                        r.meta = new Result.Meta(200, "请求成功");
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    case "exportWokcenterDetail":
                        exportWokcenterDetail(jObject);//导出工区数据
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    DataTable getData(JObject jObject)
    {
        //查询分厂下工区
        string sql = "SELECT w.workcentername,w.workcenterid FROM Workcenter w WHERE w.wctype IS NULL AND w.notes IS NULL ";

        if (jObject["originalfactoryid"] != null && jObject["originalfactoryid"].ToString() != "")
        {
            sql += string.Format(" AND w.factoryid = '{0}'", jObject["originalfactoryid"].ToString());
        }

        DataTable dtWorkcenter = dal.GetDataTable(sql);
        dtWorkcenter.Columns.Add("reportqty");//报工
        dtWorkcenter.Columns.Add("stepplanqty");//报工中已排产
        dtWorkcenter.Columns.Add("stapplanrate");//排产率

        //报工
        sql = @"
SELECT COUNT(csw.workflowstepid) qty,csw.workcenterid
FROM containerstepworkreport csw
LEFT JOIN containerstepdispatch csd ON csd.containerstepdispatchid = csw.containerstepdispatchid
LEFT JOIN factory f ON f.factoryid = csw.factoryid
LEFT JOIN Workflowstep ws ON ws.workflowstepid = csw.workflowstepid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec sp ON sp.specid = NVL(sb.revofrcdid,ws.specid)
WHERE csw.isuse = 0 AND csd.isuse = 0 
      AND ws.workflowstepname NOT LIKE '%洗%' AND ws.workflowstepname NOT LIKE '%油%' AND ws.workflowstepname NOT LIKE '%库%' 
      AND sp.lastcheck <> 1 ";
        if (jObject["originalfactoryid"] != null && jObject["originalfactoryid"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryid = '{0}'", jObject["originalfactoryid"].ToString());
        }

        // 查询时间
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND TRUNC(csw.createdate) BETWEEN to_date('{0}','yyyy-MM-dd')  AND to_date('{1}','yyyy-MM-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }
        sql += "GROUP BY csw.workcenterid";
        DataTable dtReportData = dal.GetDataTable(sql);

        //报工中已排产
        sql = @"
SELECT COUNT(csw.workflowstepid) qty,csw.workcenterid
FROM containerstepworkreport csw
LEFT JOIN Workflowstep ws ON ws.workflowstepid = csw.workflowstepid
LEFT JOIN containerstepplan cp ON cp.containerid = csw.containerid AND cp.workflowstepname = ws.workflowstepname AND cp.plantype = 1
LEFT JOIN factory f ON f.factoryid = csw.factoryid
LEFT JOIN containerstepdispatch csd ON csd.containerstepdispatchid = csw.containerstepdispatchid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec sp ON sp.specid = NVL(sb.revofrcdid,ws.specid)
WHERE csw.isuse = 0 AND csd.isuse = 0 
      AND ws.workflowstepname NOT LIKE '%洗%' AND ws.workflowstepname NOT LIKE '%油%' AND ws.workflowstepname NOT LIKE '%库%' 
      AND cp.containerstepplanid IS NOT NULL 
      AND sp.lastcheck <> 1 ";
        if (jObject["originalfactoryid"] != null && jObject["originalfactoryid"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryid = '{0}'", jObject["originalfactoryid"].ToString());
        }

        // 查询时间
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND TRUNC(csw.createdate) BETWEEN to_date('{0}','yyyy-MM-dd')  AND to_date('{1}','yyyy-MM-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }
        sql += "GROUP BY csw.workcenterid";
        DataTable dtStepPlanedData = dal.GetDataTable(sql);

        foreach (DataRow dr in dtWorkcenter.Rows)
        {
            string filter = string.Format(" workcenterid = '{0}' ", dr["workcenterid"].ToString());
            dr["reportqty"] = dtReportData.Select(filter).Length > 0 ? dtReportData.Select(filter)[0]["qty"] : 0;
            dr["stepplanqty"] = dtStepPlanedData.Select(filter).Length > 0 ? dtStepPlanedData.Select(filter)[0]["qty"] : 0;
            if (dr["reportqty"].ToString() == "0")
            {
                dr["stapplanrate"] = "--";
            }
            else
            {
                decimal repQty = Convert.ToDecimal(dr["reportqty"]);
                decimal stepPlanedQty = Convert.ToDecimal(dr["stepplanqty"]);
                dr["stapplanrate"] = ((stepPlanedQty / repQty) * 100).ToString("0.00") + "%";
            }
        }

        foreach (DataColumn col in dtWorkcenter.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        return dtWorkcenter;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        DataTable dtResult = getData(jObject);
        dtResult.Columns["workcentername"].Caption = "工区名称";
        dtResult.Columns["reportqty"].Caption = "报工数";
        dtResult.Columns["stepplanqty"].Caption = "报工中已排产";
        dtResult.Columns["stapplanrate"].Caption = "排产率";
        dtResult.Columns.Remove("workcenterid");
        ExportHelper.ExportExcel(dtResult, "各工区报工及排产率查询报表");
    }

    //导出本工区数据
    void exportWokcenterDetail(JObject jObject)
    {
        string sql = @"
SELECT w.workcentername,cci.containername,ws.workflowstepname,csp.stepplancreatedate,e.fullname,
       DECODE(csp.containerstepplanid,NULL,'未排产','已排产') isplan,
       csw.createdate,csw.qty
FROM containerstepworkreport csw
LEFT JOIN containerstepdispatch csd ON csd.containerstepdispatchid = csw.containerstepdispatchid
LEFT JOIN factory f ON f.factoryid = csw.factoryid
LEFT JOIN Workflowstep ws ON ws.workflowstepid = csw.workflowstepid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec sp ON sp.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN containercurrentinfo cci ON cci.containerid = csw.containerid
LEFT JOIN Workcenter w ON w.workcenterid = csd.workcenterid
LEFT JOIN containerstepplan csp ON csp.containerid = csw.containerid AND csp.workflowstepname = ws.workflowstepname
LEFT JOIN employee e ON e.employeeid = csp.stepplancreateemployeeid
WHERE csw.isuse = 0 AND csd.isuse = 0 
      AND ws.workflowstepname NOT LIKE '%洗%' AND ws.workflowstepname NOT LIKE '%油%' AND ws.workflowstepname NOT LIKE '%库%' 
      AND sp.lastcheck <> 1 ";
        if (jObject["originalfactoryid"] != null && jObject["originalfactoryid"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryid = '{0}'", jObject["originalfactoryid"].ToString());
        }

        if (jObject["workcentername"] != null && jObject["workcentername"].ToString() != "")
        {
            sql += string.Format(" AND w.workcentername = '{0}'", jObject["workcentername"].ToString());
        }

        // 查询时间
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND TRUNC(csw.createdate) BETWEEN to_date('{0}','yyyy-MM-dd')  AND to_date('{1}','yyyy-MM-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }

        DataTable dtResult = dal.GetDataTable(sql);
        dtResult.Columns["workcentername"].Caption = "工区";
        dtResult.Columns["containername"].Caption = "流水卡号";
        dtResult.Columns["workflowstepname"].Caption = "工序";
        dtResult.Columns["stepplancreatedate"].Caption = "排产时间";
        dtResult.Columns["fullname"].Caption = "排产人";
        dtResult.Columns["isplan"].Caption = "排产状态";
        dtResult.Columns["createdate"].Caption = "报工时间";
        dtResult.Columns["qty"].Caption = "报工数";
        ExportHelper.ExportExcel(dtResult, jObject["workcentername"].ToString() + "--报工及排产率查询报表明细");
    }
}